package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.java4less.rchart.Chart;
import com.java4less.rchart.ChartListener;
import com.java4less.rchart.ChartLoader;
import com.java4less.rchart.gc.ChartGraphics;
import com.java4less.rchart.gc.GraphicsProvider;
import com.java4less.rchart.gc.android.ChartAndroidImage;
import com.yxt.common.sys.CommConstant;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;

public class RainStationWeekChartActivity extends Activity {
	private WaterChartPanel chartPanel;
	private String code;
	private Map<String, String> station = new HashMap<String, String>();
	private StringBuffer xalias = new StringBuffer();
	private StringBuffer xvalue = new StringBuffer();
	private List<String> datelst = new ArrayList<String>();
	private ProgressDialog dialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.rain_week_chart); // 软件activity的布局
		ActivityStackControlUtil.add(this);

		Button btnBackHome = (Button) findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		initComponent();
	}

	private void downloadRainData() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new RainChartHandler());
		} catch (Exception e) {
			dialog.cancel();
			throw new InternetException("");
		}
	}

	private InputStream getInputStream() throws IOException {
		Intent intent = getIntent();
		String server = CommConstant.Sever.RAIN_SERVER;
		code = intent.getStringExtra("code");
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"rainchart.xml");
		} else {
			URL url = new URL(server + "rain/StaRDInfo.aspx?iphoneid="
					+ CommConstant.Main.CURRENT_IPHONE_CODE + "&version="
					+ CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode="
					+ CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="
					+ CommConstant.Main.CURRENT_RIVER_CODE + "&stacode=" + code);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}

	private class RainChartHandler extends DefaultHandler {
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("station".equals(localName)) {
				for (int i = 0; i < attrs.getLength(); i++) {
					station.put(attrs.getLocalName(i), attrs.getValue(i));
				}
			} else if ("rian".equals(localName)) {
				xalias.append(attrs.getValue("day").substring(5) + "|");
				xvalue.append(attrs.getValue("value") + "|");
				datelst.add(attrs.getValue("day"));
			} else if ("message".equals(localName)) {
				dialog.cancel();
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}

	private void initComponent() {
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler() {
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
					ChartAndroidImage.assets = getAssets();
					String chartfile = "rainchart.txt";
					chartPanel = new WaterChartPanel(getApplicationContext());
					try {
						chartPanel.setChart(loadFromAsset(chartfile));
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					RelativeLayout layout = (RelativeLayout) findViewById(R.id.pnlMiddle);
					layout.addView(chartPanel);
					TextView lblTitle = (TextView) findViewById(R.id.lblTitle);
					lblTitle.setText(station.get("name"));
					TextView lblStationCode = (TextView) findViewById(R.id.lblStationCode);
					lblStationCode.setText(station.get("code"));
					TextView lblStationRiver = (TextView) findViewById(R.id.lblStationRiver);
					lblStationRiver.setText(station.get("hn"));
					TextView lblStationAddr = (TextView) findViewById(R.id.lblStationAddr);
					lblStationAddr.setText(station.get("addr"));
					dialog.cancel();
				}
			}
		};

		new Thread() {
			public void run() {
				Looper.prepare();
				downloadRainData();
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m); // 给handle发送的消息
				Looper.loop();
			};

		}.start();
	}

	public Chart loadFromAsset(String name) throws IOException {
		InputStream is = getAssets().open(name);
		ChartLoader loader = new ChartLoader();
		loader.loadFromFile(is, true);
		loader.setParameter("TITLECHART", "最近一周雨量过程");
		loader.setParameter("XAXIS_LABELS", xalias.substring(0,xalias.length() - 1));
		loader.setParameter("SERIE_DATA_1", xvalue.substring(0,xvalue.length() - 1));
		loader.setParameter("SERIE_1", "时间");
		Chart chart = loader.build(false, false);
		chart.setWidth(LayoutParams.FILL_PARENT);
		chart.setHeight(LayoutParams.FILL_PARENT);
		return chart;
	}

	public class WaterChartPanel extends View implements ChartListener,
			android.view.View.OnClickListener,
			android.view.View.OnTouchListener {
		private Chart chart;

		public WaterChartPanel(Context context) {
			super(context);
			chart = null;
			setClickable(true);
			setOnTouchListener(this);
		}

		public Chart getChart() {
			return chart;
		}

		public void setChart(Chart c) {
			if (chart != null)
				chart.removeChartListener(this);
			chart = c;
			chart.addChartListener(this);
			chart.activateSelection = true;
		}

		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
			chart.setWidth(w);
			chart.setHeight(h);
		}

		protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
			setMeasuredDimension(chart.getWidth(), chart.getHeight());
		}

		public void onDraw(Canvas g) {
			super.onDraw(g);
			if (g == null)
				return;
			try {
				ChartGraphics g2 = GraphicsProvider.getGraphics(g);
				chart.doubleBuffering = false;
				chart.paint(g2);
				g2.dispose();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return;
		}

		public void paintUserExit(Chart chart1, ChartGraphics chartgraphics) {
		}

		public void chartEvent(Chart c, int type) {
			if (WaterChartPanel.EVENT_POINT_CLICKED == type) {
				int point = chart.selectedSeriePoint;
				if (point > -1) {
					Intent intent = new Intent();
					intent.setClass(getApplicationContext(), RainStationDayChartActivity.class);
					intent.putExtra("code", code);
					intent.putExtra("endtime", datelst.get(point));
					startActivity(intent);
				}
			} 
		}

		public void onClick(View v) {

		}

		public boolean onTouch(View v, MotionEvent e) {
			if (e.getAction() == 0 && chart != null) {
				float x = e.getX();
				float y = e.getY();
				chart.mouseMoved((int) x, (int) y);
				chart.mouseClick();
				return true;
			} else {
				return false;
			}
		}

	}

	protected void onDestroy() {
		super.onDestroy();
		ActivityStackControlUtil.remove(this);
	}
}